package com.hanshg.cherry.mapper;

import com.hanshg.cherry.mapper.base.MyBaseMapper;
import com.hanshg.cherry.model.SysPermission;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 许可映射器
 *
 * @author 柠檬水
 * @date 2020/04/13
 */
@Mapper
public interface PermissionMapper extends MyBaseMapper<SysPermission> {

    /**
     * 找到所有
     *
     * @return {@link List<SysPermission>}
     */
    @Select("select * from sys_permission t order by t.sort")
    List<SysPermission> findAll();

    /**
     * 数菜单
     *
     * @return {@link Integer}
     */
    @Select("select count(*) from sys_permission t where t.type='1'")
    Integer countMenu();

    /**
     * 计数按钮
     *
     * @return {@link Integer}
     */
    @Select("select count(*) from sys_permission t where t.type='2'")
    Integer countButton();

    /**
     * 通过角色id列表
     *
     * @param roleId 角色id
     * @return {@link List<SysPermission>}
     */
    @Select("select p.* from sys_permission p inner join sys_role_permission rp on p.id = rp.permissionId where rp.roleId = #{roleId} order by p.sort")
    List<SysPermission> listByRoleId(Long roleId);

    /**
     * 保存
     *
     * @param e e
     * @return int
     */
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into sys_permission(parentId, name, css, href, type, permission, sort) values(#{parentId}, #{name}, #{css}, #{href}, #{type}, #{permission}, #{sort})")
    int save(SysPermission e);

    /**
     * 获得系统权限的id
     *
     * @param id id
     * @return {@link SysPermission}
     */
    @Select("select * from sys_permission t where t.id = #{id}")
    SysPermission getSysPermissionById(Long id);

    /**
     * 更新许可
     *
     * @param sysPermission 系统权限
     * @return int
     */
    int updatePermission(SysPermission sysPermission);

    /**
     * 删除权限的id
     *
     * @param id id
     * @return int
     */
    @Delete("delete from sys_permission where id = #{id}")
    int deletePermissionById(Long id);

    /**
     * 按父id删除
     *
     * @param parentId 父id
     * @return int
     */
    @Delete("delete from sys_permission where parentId = #{parentId}")
    int deleteByParentId(Long parentId);

    /**
     * 通过用户id列表
     *
     * @param userId 用户id
     * @return {@link List<SysPermission>}
     */
    @Select("SELECT DISTINCT sp.*  " +
            "FROM sys_role_user sru " +
            "INNER JOIN sys_role_permission srp ON srp.roleId = sru.roleId " +
            "LEFT JOIN sys_permission sp ON srp.permissionId = sp.id " +
            "WHERE " +
            "sru.userId = #{userId} order by sp.sort")
    List<SysPermission> listByUserId(@Param("userId") Long userId);
}
